#coding:utf-8

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf


#自动下载并导入数据
mnist=input_data.read_data_sets('./datas/mnist/',one_hot=True)

#hyper Parameters
learning_rate=0.05
num_steps=500
batch_size=64
display_step=100

#Network paramepters
hiddern_1=256 #1st layer number of neurons
hiddern_2=256 #2nd layer number of neurons

inputs=784 #mnist data input ,img shape 28*28
outputs=10 #mnist total classes ,0-9 digits

#tf graph input
X=tf.placeholder('float',[None,inputs])
Y=tf.placeholder('float',[None,outputs])

#Store layers weight & bias
weights={
    'h_01':tf.Variable(tf.random_normal([inputs,hiddern_1])),
    'h_12':tf.Variable(tf.random_normal([hiddern_1,hiddern_2])),
    'h_23':tf.Variable(tf.random_normal([hiddern_2,outputs]))
}
biases={
    'b_01':tf.Variable(tf.random_normal([hiddern_1])),
    'b_12':tf.Variable(tf.random_normal([hiddern_2])),
    'b_23':tf.Variable(tf.random_normal([outputs]))
}


def create_nn(x):
    #hidden fully connected layer with 256 neurons
    layer_1=tf.add(tf.matmul(x,weights['h_01']),biases['b_01'])
    # hidden fully connected layer with 256 neurons
    layer_2=tf.add(tf.matmul(layer_1,weights['h_12']),biases['b_12'])
    #output fully connected layer with a neron for each class
    out_layer=tf.matmul(layer_2,weights['h_23'])+biases['b_23']
    return out_layer

#construct model
logits=create_nn(X)

#define loss and optimizer
loss_op=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=Y))

optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op=optimizer.minimize(loss_op)

#evaluate model (with test logits ,for dropout to disabled)
correct_pred=tf.equal(tf.argmax(logits,1),tf.argmax(Y,1))
accuracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32))

init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for step in range(1,num_steps+1):
        batch_x,batch_y=mnist.train.next_batch(batch_size)
        #run optimizaiton op ->backprop
        sess.run(train_op,feed_dict={X:batch_x,Y:batch_y})

        if step % display_step == 0 or step == 1:
            # Calculate batch loss and accuracy，计算每一批数据的误差及准确度
            loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
                                                                 Y: batch_y})
            print("Step " + str(step) + ", Minibatch Loss= " + \
                  "{:.4f}".format(loss) + ", Training Accuracy= " + \
                  "{:.3f}".format(acc))

    print("Optimization Finished!")
    # Calculate accuracy for MNIST test images，计算测试数据上的准确度
    print("Testing Accuracy:", \
          sess.run(accuracy, feed_dict={X: mnist.test.images,
                                        Y: mnist.test.labels}))